package com.mishow.net;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.AuthFailureError;
import com.mishow.log.MyLog;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.DeviceUtil;
import com.mishow.utils.MD5;
import com.mishow.volley.http.RequestManager;
import com.mishow.volley.http.request.RequestExtension;
/**
 * 
 * 作者：wei.miao<br/>
 * 描述：网络请求工具类
 */
public class NetworkUtil {

	private static final String TAG = NetworkUtil.class.getSimpleName();
	private static final String GET_ENCODE = "UTF-8";
	
	private NetworkUtil() {
		
	}
	
	/**
	 * 生成GET请求URL
	 * @param context 上下文环境
	 * @param url 请求地址
	 * @param params 请求参数
	 * @return
	 */
	public static String getRequestUrl(Context context, String url, Map<String, Object> params) {
		return url + generaterGetRequestParams(context, params);
	}
	
	/**
	 * 生成GET请求参数
	 * @param context
	 * @param params
	 * @return
	 */
	private static String generaterGetRequestParams(Context context, Map<String, Object> params) {
		String requestParams = "?dataJson=";
		try {
			JSONObject head = generaterHead(context);
			JSONObject body = generaterBody(params);
			
			JSONObject jsonRequestParams = new JSONObject();
			jsonRequestParams.put("head", head);
			jsonRequestParams.put("body", body);
			jsonRequestParams.put("mac", getSign(head, body));
			String dataJson = jsonRequestParams.toString();
			
			requestParams = requestParams + URLEncoder.encode(dataJson, GET_ENCODE);
		} catch (UnsupportedEncodingException e) {
			MyLog.d(TAG, "编码格式异常：" + e.getMessage());
		}
		return requestParams;
	}
	
	
	/**
	 * 生成Post请求URL
	 * @param context 上下文环境
	 * @param url 请求地址
	 * @param params 请求参数
	 * @return
	 */
	public static String postRequestUrl(Context context, String url, Map<String, String> params) {
		return url + generaterPostRequestParams(context, params);
	}
	
	/**
	 * 生成POST请求参数
	 * @param context
	 * @param params
	 * @return
	 */
	public static Map<String, String> generaterPostRequestParams(Context context, Map<String, String> params) {
		/*JSONObject head = generaterHead(context);
		JSONObject body = generaterBody(params);
		
		JSONObject jsonRequestParams = new JSONObject();
		jsonRequestParams.put("head", head);
		jsonRequestParams.put("body", body);
		jsonRequestParams.put("mac", getSign(head, body));
		String dataJson = jsonRequestParams.toString();
		
		HashMap<String, String> requestParams = new HashMap<String, String>();
		requestParams.put("dataJson", dataJson);
		MyLog.d("requestParams", requestParams + "");*/
		return params;
	}
	
	/**
	 * 将H5中的请求参数进行封包签名
	 * @param context
	 * @param jsonData
	 * @return
	 */
	public static String getHtmlPostRequestParams(Context context, String jsonData) {
		Map<String, Object> params = (Map<String, Object>) JSON.parse(jsonData);
		JSONObject head = generaterHead(context);
		JSONObject body = generaterBody(params);
		
		JSONObject jsonRequestParams = new JSONObject();
		jsonRequestParams.put("head", head);
		jsonRequestParams.put("body", body);
		jsonRequestParams.put("mac", getSign(head, body));
		return jsonRequestParams.toString();
	}
	
	/**
	 * 生成头部信息
	 * @param context
	 * @return
	 */
	private static JSONObject generaterHead(Context context) {
		JSONObject jsonHead = new JSONObject();
		jsonHead.put("serialNumber", "120319181305000011");
		jsonHead.put("method", "142005");
		jsonHead.put("version", "1");
		jsonHead.put("terminalstate", "0");
		jsonHead.put("imei", AndroidUtil.getImei(context));
		jsonHead.put("sysVersion", android.os.Build.VERSION.RELEASE);
		jsonHead.put("appVersion", AndroidUtil.getVersionCode(context));
		jsonHead.put("appSys", "2");//客户端类型(IOS=1,Andorid=2)
		return jsonHead;
	}
	
	/**
	 * 生成Body信息
	 * @param params
	 * @return
	 */
	private static JSONObject generaterBody(Map<String, Object> params) {
		JSONObject body;
		if (params == null) {
			body = new JSONObject(0);
		} else {
			body = new JSONObject(params);
		}
		return body;
	}
	
	public static void executeRequest(Context context, RequestExtension<?> request) {
		executeRequest(context, request, TAG);
	}
	
	public static void executeRequest(Context context, RequestExtension<?> request, Object tag) {
		String userAgentStuff = getAppendUserAgent(context);
		try {
			Map<String, String> requestHeaders = request.getHeaders();
			String userAgent = requestHeaders.get("User-Agent");
			userAgent = (userAgent == null) ? userAgentStuff : (userAgent + userAgentStuff);
			Map<String, String> headers = new HashMap<String, String>();
			headers.putAll(requestHeaders);
			headers.put("User-Agent", userAgent);
			request.setHeaders(headers);
		} catch (AuthFailureError e) {
			MyLog.e(TAG, e.getMessage());
		}
		RequestManager.getInstance().addRequest(request, tag);
	}
	
	public static void cancelRequest(Object tag) {
		RequestManager.getInstance().cancelAll(tag);
	}
	
	private static String getAppendUserAgent(Context context) {
		String appName = "Mishow";
		String appVersion = AndroidUtil.getVersionName(context);
		String osName = "Android";
		String osVersion = android.os.Build.VERSION.RELEASE;
		String deviceBrand = android.os.Build.BRAND;
		String deviceModel = android.os.Build.MODEL;
		String deviceResolution = (int) DeviceUtil.getDeviceHight(context) + "*" + (int) DeviceUtil.getDeviceWidth(context);
		StringBuilder sb = new StringBuilder();
		sb.append(deviceBrand).append("/").append(deviceModel).append("/").append(deviceResolution).append(" ")
				.append(osName).append("/").append(osVersion).append(" ").append(appName).append("/").append(appVersion);
		return sb.toString();
	}
	
	/**
	 * 获取签名
	 * @param head
	 * @param body
	 * @return
	 */
	public static String getSign(JSONObject head, JSONObject body) {
		String jsonHead = head.toString();
		String jsonBody = body.toString();
		String secret = "mishow";
		String publicText = jsonHead + jsonBody + secret;
		String md5Text = MD5.md5(publicText);
		int start = md5Text.length() - 8;// 截取末尾8个字符
		String sign = md5Text.substring(start);
		return sign;
	}
	
}
